const express = require('express');
const router = express.Router();
const multer = require("multer");
const path = require("path");
const db = require("../model/db");

// 查询该商品订单的详细信息
router.get("/:id", async (req, res) => {
    const data = await db.GoodsOrder.findById(req.params.id).populate("Goods").populate("Host").populate("Shop");
    res.send({
        code: 0,
        message: "",
        data
    });
})


// 添加商品订单
router.post("/", async (req, res) => {
    const data = await db.GoodsOrder.create(req.body);
    res.send({
        code: 0,
        message: "",
        data
    });
})


//修改商品订单信息
router.put("/:id", async (req, res) => {
    await db.GoodsOrder.updateOne({
        _id: db.ObjectId(req.params.id)
    }, req.body); //(要修改的对象)
    res.send(true);
})


// 注销（删除）商品订单
router.delete("/:id", async (req, res) => {
    await db.GoodsOrder.deleteOne({
        _id: req.params.id
    });
    res.send(true);
})


// 得到所有商品订单
router.get("/", async (req, res) => {
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    let contion = {}; //条件对象
    if (req.query.key) {
        contion = {
            name: req.query.key.toUpperCase()
        }
    }
    let condition = {};
    if (req.query.key) {
        const exp = new RegExp(req.query.key, "i");
        condition = {
            $or: [{
                nickname: {
                    $regex: exp
                }
            },
            {
                mobile: {
                    $regex: exp
                }
            },
            {
                name: {
                    $regex: exp
                }
            }
            ]
        };
    }
    const data = await db.GoodsOrder.find(condition).skip((page - 1) * limit).limit(limit).populate("Goods").populate("Host").populate("Shop");
    const count = await db.GoodsOrder.count(condition);
    res.send({
        code: 0,
        message: "",
        data
    });
})




module.exports = router;